import axios from 'axios'
import { Message } from 'element-ui';
import {Loading} from 'element-ui'
const instance  = axios.create({
  baseURL:'https://api.shop.eduwork.cn',
  timeout:'5000',
});

let loading;
//内存中正在请求的数量
let loadingNum=0;
function startLoading() {    
    if(loadingNum==0){
        loading = Loading.service({
          lock: true,
          text: '拼命加载中...',
          background:'rgba(255,255,255,0.5)',
        })
    }
    //请求数量加1
    loadingNum++;
}
function endLoading() {
    //请求数量减1
    loadingNum--
    if(loadingNum<=0){
        loading.close()
    }
}
//请求拦截器
instance.interceptors.request.use((config)=>{
  // instance.defaults.withCredentials = true;
  let token = localStorage.getItem('shuchotaitoken')
  if(token){
    config.headers.authorization = `Bearer ${token}`;
  }
  startLoading();
  return config
},(error)=>{return Promise.reject(error)} )

//响应拦截器
instance.interceptors.response.use((response)=>{
  endLoading();
  return response
},
(error)=>{
  //拦截错误，提示用户
    if(error.response.status==401){
      localStorage.setItem('shuchotaitoken','')
    Message({
      showClose: true,
      message: '用户没有权限（令牌、用户名、密码错误）'
    });
  }else if(error.response.status==400){
    Message({
      showClose: true,
      message: '创建分类失败，不能超过二级分类'
    });
  }
return Promise.reject(error)
})
export default
  instance